//
//  ComposeViewController.swift
//  Sina
//
//  Created by 王杰 on 15/11/19.
//  Copyright © 2015年 王杰. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
class ComposeViewController: UIViewController {
    
    private lazy var keyBoardView: EmoticonKeyBoardView = EmoticonKeyBoardView {[weak self] (em) -> () in
        self?.textView.insertAttrText(em)

    }
    //点击toolbar发布图片按钮的监听方法的实现
    @objc private func selectPicture() {
    
    selectorVC.view.snp_updateConstraints { (make) -> Void in
        make.height.equalTo(224 + 80 + 40)
        }
    }
    @objc private func selectEmoticon() {
    
    textView.resignFirstResponder()
        textView.inputView = (textView.inputView == nil ? keyBoardView : nil)

        textView.becomeFirstResponder()

    }
    //关闭按钮的点击事件
    @objc private func close() {
    
    dismissViewControllerAnimated(true, completion: nil)
    
    }
    //发布按钮事件
    @objc private func send() {
    //图片的发布
        guard let token = UserAccountViewModel().token else {
            SVProgressHUD.showErrorWithStatus("先登录一下吧")
            return
        }
        let parmaters = ["access_token": token,"status": textView.fulltext()]

        if selectorVC.imageList.count >= 1 {
            
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"

            let imageData = UIImagePNGRepresentation(selectorVC.imageList[0])
            //网络请求任务
            NetworkTools.sharedTools.uploadImage(urlString, parmaters: parmaters, imageData: imageData!, finished: { (result, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("先登录一下吧")
                    return
                }
                SVProgressHUD.showSuccessWithStatus("发布Weibo成功")
                self.dismissViewControllerAnimated(true, completion: nil)

            })
            
        } else {
            
            //没有图片
            let urlString = "https://api.weibo.com/2/statuses/update.json"
            NetworkTools.sharedTools.requestJsonDict(.POST, urlString: urlString, parmaters: parmaters) { (result, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus(AppErrorTip)
                    return
                }
                SVProgressHUD.showSuccessWithStatus("发布Weibo成功")
                self.dismissViewControllerAnimated(true, completion: nil)
                print(result)
            }
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        
        setupUI()
    }
    //设置frame
    
    override func viewDidAppear(animated: Bool) {
        
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
        
    }
    //设置UI
    private func setupUI() {
        
        //添加导航条
        setNavBar()
        //添加文本输入框
        setupTextView()
        //添加toolBar
        setupToolBar()
        //添加一个视图控制器
        setSelectorView()
        //注册一个通知
        registerNotification()
    }
    
    private func setSelectorView() {
        addChildViewController(selectorVC)
        view.addSubview(selectorVC.view)
        
        view.bringSubviewToFront(toolBar)
        selectorVC.view.snp_makeConstraints { (make) -> Void in make.left.bottom.right.equalTo(view)
            make.height.equalTo(0)
        }
    }
    //监听一个通知
    private func registerNotification() {
    
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    
    }
    
    deinit {
    
    NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }
    
    @objc private func keyboardWillChange(n: NSNotification) {
        
        print(n)
        
        let duration = n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! Double
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        let curve = n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! Int
        //获取键盘高度
        let offset = -screenH + rect.origin.y
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(offset)
            
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
          
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)

            self.view.layoutIfNeeded()
        }

    }
    //懒加载控件
    
    private lazy var textView: EmoticonTextView = {
        
    let lv = EmoticonTextView()
        lv.delegate = self
        lv.font = UIFont.systemFontOfSize(18)
        lv.textColor = UIColor.darkGrayColor()
        
        //回退键盘的处理模式
        lv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        lv.alwaysBounceVertical = true

        return lv
    
    }()

    //添加占位文本
    private lazy var placeHolderLabel: UILabel = UILabel(title: "分享新鲜事...", size: 18, color: UIColor.lightGrayColor())
    //工具条
    private lazy var toolBar: UIToolbar = UIToolbar()

    private lazy var selectorVC: PictureSelectorViewController = PictureSelectorViewController()
}

extension ComposeViewController:UITextViewDelegate {

    func textViewDidChangeSelection(textView: UITextView) {
        
        placeHolderLabel.hidden = textView.hasText()
        
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }

}
extension ComposeViewController {

    //设置底部的工具栏
    private func setupToolBar() {
    
    view.addSubview(toolBar)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(40)
        }
        //设置toolBar的内容和点击事件(字典传值)
        var items = [UIBarButtonItem()]
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","actionName": "selectEmoticon"],
            ["imageName": "compose_add_background"]]
        
        for dict in itemSettings {
        
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])

        items.append(item)
            
        let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        
        items.removeLast()
        
        toolBar.items = items
    }
    
    private func setupTextView() {
        
        view.addSubview(textView)
//        textView.backgroundColor = UIColor.randomColor()
        
        textView.snp_makeConstraints { (make) -> Void in
            
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(view.bounds.height / 3)
        }
        
        textView.addSubview(placeHolderLabel)
        
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    
    //设置导航条

    private func setNavBar() {
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")
        
        self.navigationItem.rightBarButtonItem?.enabled = false
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        navigationItem.titleView = titleView
        
        //titleView中的内容
        let nameLabel = UILabel(title: UserAccountViewModel().userName ?? "", size: 14, color: UIColor.greenColor(), margin: 0)
        let titleLabel = UILabel(title: "发微博", size: 14, color: UIColor.darkGrayColor())
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
    }
    

}




